import React, { useEffect, useState } from 'react';
import { FormInstance } from 'antd';
import Modal from '@/components/Modal';
import { getCommandKey } from '@/utils';
import CreateForm from '@/components/CreateForm';

interface CreateModalProps {
  visible?: boolean;
  data?: ProjectItem;
  onCancel?: () => void;
  onOk?: (val: ProjectItem) => void;
  loading?: boolean;
  cateList: CateItem[];
}

const CreateModal: React.FC<CreateModalProps> = ({
  visible = false,
  data,
  onCancel,
  onOk,
  loading,
  cateList,
}) => {
  const [form, setForm] = useState<FormInstance>();
  const { id } = data || {};

  const submit = () => {
    form?.validateFields().then((res) => {
      const params = { ...data, ...res };
      const { commands } = params;
      commands.forEach((cmd: CommandItem) => {
        cmd.key = getCommandKey(params.code, cmd.value);
      });
      onOk && onOk(params);
    });
  };

  const cancel = () => {
    onCancel && onCancel();
  };

  useEffect(() => {
    if (!visible) {
      form?.resetFields();
    }
  }, [visible]);

  return (
    <Modal
      width={500}
      title={!id ? '新增项目' : '编辑项目'}
      visible={visible}
      onCancel={cancel}
      onOk={submit}
      loading={loading}
    >
      <CreateForm onLoad={setForm} data={data} cateList={cateList} />
    </Modal>
  );
};

export default React.memo(CreateModal);
